<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\RoleRequest;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * 角色控制器
 * Class RoleController
 * @package App\Http\Controllers\Admin
 */
class RoleController extends Controller
{
	/**
	 * Display a listing of the resource.
	 * @return \Illuminate\Http\Response
	 */
	public function index() {
		$data = Role::all(['id', 'name']);
		return view('admin.role.index', compact('data'));
	}

	/**
	 * Show the form for creating a new resource.
	 * @return \Illuminate\Http\Response
	 */
	public function create() {
		return view('admin.role.create');
	}

    /**
     * Store a newly created resource in storage.
     * @param RoleRequest $request
     * @return array
     */
	public function store(RoleRequest $request) {
		$res = Role::create($request->all());
		if ($res) {
			return ['status' => 0, 'msg' => '成功'];
		}
		return ['status' => 1, 'msg' => '失败'];
	}

	/**
	 * Display the specified resource.
	 * @param  int $id
	 * @return \Illuminate\Http\Response
	 */
	public function show($id) {
		return Role::with('permissions')->where('id', $id)->get();
	}

	/**
	 * Show the form for editing the specified resource.
	 * @param  int $id
	 * @return \Illuminate\Http\Response
	 */
	public function edit($id) {
		$model = new Role();
		$data = $model->where('id', $id)->with('permissions')->first();
		// 权限列表
		$permissions = Permission::get(['id', 'pid', 'name', 'is_menu'])->toArray();
		$permissions = subMenu($permissions);

		return view('admin.role.edit', compact('data', 'permissions'));
	}

	/**
	 * Update the specified resource in storage.
	 * @param  \Illuminate\Http\Request $request
	 * @param  int                      $id
	 * @return \Illuminate\Http\Response
	 */
	public function update(Request $request, Role $role) {
		$ids = $request->get('permissions');
		$role->permissions()->sync($ids);
		return response()->json(['status' => 0, 'msg' => '成功']);
	}

    /**
     * Remove the specified resource from storage.
     * @param Role $role
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
	public function destroy(Role $role) {
		$res = $role->delete();
		if ($res) {
			return response()->json(['status' => 0, 'msg' => '成功']);
		}
		return response()->json(['status' => 1, 'msg' => '失败']);
	}
}
